/**
 * @desc: 供应商商品搜索search
 * @author: fj
 */
import React, {
  useState,
  useEffect,
  forwardRef,
  useImperativeHandle,
} from 'react';
import { Popover, Input, Tooltip, Select } from 'antd';
import { querySysSkuList } from '../service';
import { customTrimFunc } from '@/utils/utils.jsx';

const { Option } = Select;

let timeout;

const SysGoodsSelect = ({ onChange }, ref) => {
  const [goodsList, setGoodsList] = useState([]); //下拉获取的商品data

  const [loading, setLoading] = useState(false);

  useImperativeHandle(ref, () => ({
    sysGoodInfoList: {
      goodsList,
    },
  }));

  const fetch = (value, callback) => {
    if (timeout) {
      clearTimeout(timeout);
      timeout = null;
    }
    const fake = async () => {
      setLoading(true);
      let res;
      //去除空格
      const newParams = customTrimFunc({
        goodsName: value,
      });
      res = await querySysSkuList(newParams);
      if (res.success) {
        const { data = [] } = res;
        callback(data);
      } else {
        callback([]);
      }
      setLoading(false);
    };

    timeout = setTimeout(fake, 300);
  };

  useEffect(() => {
    handleSearch();
  }, []);

  //搜索数据
  const handleSearch = (value) => {
    // if (value) {
    fetch(value, (data) => {
      setGoodsList(data);
    });
    // }
  };

  const handleChange = (value) => {
    onChange(value);
  };

  const options = (goodsList || []).map((d) => (
    <Option value={d.spuId} key={d.id} label={d.goodsName}>
      <Tooltip title={d.goodsName}>{d.goodsName}</Tooltip>
    </Option>
  ));

  return (
    <Select
      showSearch
      placeholder="请输入系统spu商品名称"
      defaultActiveFirstOption={false}
      showArrow={false}
      style={{ width: '200px' }}
      filterOption={false}
      onSearch={handleSearch}
      onChange={handleChange}
      notFoundContent={loading ? '加载中...' : '暂无数据'}
    >
      {options}
    </Select>
  );
};

export default forwardRef(SysGoodsSelect);
